package com.leyou.sms.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties prop;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.Queue.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(value = MQConstants.Exchange.SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.VERIFY_CODE_KEY
    ))
    public void listenVerifyCode(Map<String, String> msg) {
        // 获取phone和code
        String phone = msg.get("phone");
        String code = msg.get("code");
        // 校验数据
        if (!RegexUtils.isPhone(phone)) {
            // 手机号格式不正确
            log.error("发送短信中止，手机号【{}】格式不正确！", phone);
            return;
        }
        if (!RegexUtils.isValidCode(code)) {
            // 验证码格式不正确
            log.error("发送短信中止，验证码【{}】格式不正确！", code);
            return;
        }
        // 准备JSON数据
        String param = "{\"code\": \"" + code + "\"}";

        // 发送短信
        smsUtils.sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(), param);
    }
}
